/*
 * @Descripttion:
 * @Author: tanwei
 * @Date: 2020-07-04 12:23:59
 * @LastEditors: tanwei
 * @LastEditTime: 2020-07-17 14:09:47
 * @FilePath: /egg/admin/app/middleware/jwtVerify.js
 */
'use strict';
const jwt = require('jsonwebtoken');
module.exports = () => {
  return async function jwtVerify(ctx, next) {
    const { request, app, helper } = ctx;
    const authorization = request.header.authorization;
    console.log(request.path);
    if (request.url.indexOf('/api') === -1) {
      await next();
      return;
    }
    if (authorization) {
      const token = authorization;
      console.log(token);
      const userInfo = await verifyToken(token, app.config.jwt.secret);
      // token过期 TokenExpiredError，无效的token JsonWebTokenError
      if (userInfo.name === 'TokenExpiredError' || userInfo.name === 'JsonWebTokenError') {
        helper.render(401);
        return;
      }
      ctx.locals.auth = userInfo;
      await next();
    } else {
      helper.render(422, {}, '用户未登录');
    }
  };

  async function verifyToken(token, secret) {
    try {
      const userInfo = jwt.verify(token, secret, (err, decoded) => {
        if (err) {
          // 'TokenExpiredError' //token过期
          // 'JsonWebTokenError' //无效的token
          return {
            name: err.name,
          };
        }
        return decoded;
      });
      return userInfo;
    } catch (e) {
      // console.error(e);
    }
    return;
  }
};
